﻿using Core;
using UnityEngine;

namespace g_gongjianta
{
    public class SkillComponent : Core.Component, IAwake, IFrameUpdate
    {
        private SkillObject curr;

        private TblSkill tbl;
        private Unit unit;
        private ICharacter character;

        public void Awake()
        {
            unit = Entity as Unit;
            Debug.Assert(unit != null);
            
            character = Entity as ICharacter;
            Debug.Assert(character != null);

            tbl = character.TblSkill;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            if (curr != null)
            {
                curr.Exit();
                curr.Dispose();
            }
            curr = null;
            tbl = null;
        }

        public bool IsRunning(long srl)
        {
            if (curr == null)
            {
                return false;
            }
            return curr.InstanceId == srl;
        }

        public SkillObject Get(long srl)
        {
            if (curr == null || curr.InstanceId != srl)
            {
                return null;
            }

            return curr;
        }

        public long Use(int skill_id)
        {
            //if (unit is Duck)
            //{
            // log.err($"Anchor Use skill_id={skill_id}");
            //}
            var conf = tbl.Find(skill_id);
            if (conf == null) return 0;

            if (curr != null)
            {
                curr.Exit();
                curr.Dispose();
            }

            curr = unit.Create<SkillObject, TblSkill.Conf>(conf);

            curr.Enter();

            return curr.InstanceId;
        }

        public void Tick()
        {
            if (curr == null)
            {
                return;
            }

            curr.Tick();

            if (curr.IsComplete)
            {
                curr.Exit();
                curr.Dispose();
                curr = null;
            }
        }
    }
}
